import uuid
import base64

from datetime import datetime

from flask import Flask, request

from tools.controller import *
from concurrent.futures import ThreadPoolExecutor
from tools.to_log import log, traffic_log

app = Flask(__name__)


def myThread(obj):
    cpu_count = os.cpu_count()
    pool = ThreadPoolExecutor(2 * cpu_count)
    pool.submit(contract_ext, obj).add_done_callback(return_data)


# pdf图片转文字
def extract_and_image(pdf_path):
    # 打开PDF
    pdf_bytes = pdf_path.read()
    words, first_page = pdf2txt(pdf_bytes)
    return words, first_page


def contract_ext(file_obj):
    pdf_data = file_obj['pdf_data']
    contract_id = file_obj['contract_id']
    try:
        words, first_page = extract_and_image(pdf_data)

        fields_list = asyncio.run(do_ext(words, first_page))
    except Exception as e:
        return return_code(500, contract_id, "服务器异常，请稍后重试")
    fields_obj = {}
    for i in fields_list:
        fields_obj.update(i)

    return return_code(200, contract_id, fields_obj)


@app.route('/get_traffic/', methods=['GET'])
def get_traffic():
    traffic = request.args.get('traffic', '')
    random_uuid = str(uuid.uuid4())
    data_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if traffic == '':
        traffic_log.info({"id": random_uuid, "date": data_time,
                          "detail": '执行时间：' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '调用状态：失败'})

        return {'code': 500, 'message': '参数错误'}
    traffic_log.info({"id": random_uuid, "date": data_time,
                      "detail": traffic})

    return {'code': 200, 'message': '访问成功'}


# 上传pdf接口，
@app.route('/upload_contract', methods=['POST', 'GET'])
def post_pg():
    log.info('upload_contract is start')
    contract_id = request.values.get('contract_id', '')
    if contract_id == '':
        log.info(u'upload_contract error is 请上传合同ID')
        return get_code('500', '请上传合同ID')
    if 'file' not in request.files:
        log.info(u'upload_contract error is 请上传文件')
        return get_code('500', '请上传文件')
    pdf_path = request.files['file']
    pdf_path.seek(0)
    magic_number = pdf_path.read(4)

    if magic_number != b'%PDF':
        log.info(u'upload_contract error is 请传入正确的文件格式')
        return get_code(500, '请传入正确的文件格式')
    try:
        myThread({'contract_id': contract_id, 'pdf_data': pdf_path})
    except Exception as e:
        log.info(u'upload_contract error is 服务器错误 -- ' + str(e))
        return get_code(500, '服务器错误')
    log.info(u'upload_contract is success')
    return get_code(200, '调用成功')


@app.route('/abc', methods=["POST"])
def get_ht():
    data = request.data
    print(request)
    print(data)
    return "200"


if __name__ == '__main__':
    app.run(debug=True, port=5000, host='0.0.0.0')
